#!/usr/bin/env node

import fetch from 'node-fetch';

const SERVER_URL = 'http://localhost:3000';

async function testMCPService() {
    console.log('🧪 Testing MCP Java Decompiler Service...\n');
    
    // 1. Health Check
    console.log('1️⃣ Testing health endpoint...');
    try {
        const healthRes = await fetch(`${SERVER_URL}/health`);
        const health = await healthRes.json();
        console.log('✅ Health check passed:', health.status);
    } catch (error) {
        console.error('❌ Health check failed:', error.message);
        return;
    }
    
    // 2. Initialize session
    console.log('\n2️⃣ Initializing MCP session...');
    let sessionId;
    try {
        const initRes = await fetch(`${SERVER_URL}/mcp`, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({
                jsonrpc: '2.0',
                id: 'init-test',
                method: 'initialize',
                params: {
                    protocolVersion: '2025-03-26',
                    capabilities: {}
                }
            })
        });
        const initData = await initRes.json();
        sessionId = initData.result?.sessionId;
        console.log('✅ Session initialized:', sessionId);
    } catch (error) {
        console.error('❌ Session initialization failed:', error);
        return;
    }
    
    // 3. List tools
    console.log('\n3️⃣ Listing available tools...');
    try {
        const toolsRes = await fetch(`${SERVER_URL}/mcp`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Mcp-Session-Id': sessionId
            },
            body: JSON.stringify({
                jsonrpc: '2.0',
                id: 'list-tools',
                method: 'tools/list',
                params: {}
            })
        });
        const toolsData = await toolsRes.json();
        const tools = toolsData.result?.tools || [];
        console.log(`✅ Found ${tools.length} tool(s):`);
        tools.forEach(tool => {
            console.log(`   - ${tool.name}: ${tool.description}`);
        });
    } catch (error) {
        console.error('❌ List tools failed:', error);
    }
    
    // 4. Test find_class_in_local_repository (small test)
    console.log('\n4️⃣ Testing class search (looking for "Test" classes)...');
    try {
        const searchRes = await fetch(`${SERVER_URL}/mcp`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Mcp-Session-Id': sessionId
            },
            body: JSON.stringify({
                jsonrpc: '2.0',
                id: 'search-class',
                method: 'tools/call',
                params: {
                    name: 'find_class_in_local_repository',
                    arguments: {
                        className: 'Test'
                    }
                }
            })
        });
        const searchData = await searchRes.json();
        
        if (searchData.error) {
            console.log('⚠️  Search returned error:', searchData.error.message);
        } else {
            const result = JSON.parse(searchData.result?.content?.[0]?.text || '{}');
            console.log(`✅ Search completed:`);
            console.log(`   - Repository: ${result.repositoryPath}`);
            console.log(`   - Index ready: ${result.indexReady}`);
            console.log(`   - Matches found: ${result.matchesFound || 0}`);
            if (result.classes && result.classes.length > 0) {
                console.log(`   - First match: ${result.classes[0].fullName}`);
            }
        }
    } catch (error) {
        console.error('❌ Class search failed:', error);
    }
    
    // 5. Cleanup session
    console.log('\n5️⃣ Cleaning up session...');
    try {
        await fetch(`${SERVER_URL}/mcp/session/${sessionId}`, {
            method: 'DELETE'
        });
        console.log('✅ Session cleaned up');
    } catch (error) {
        console.error('⚠️  Session cleanup failed:', error.message);
    }
    
    console.log('\n✨ Test completed!');
}

testMCPService().catch(console.error);